3 * MediaWiki page data importer.
5 * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
24 * @ingroup SpecialPage
28 * XML file reader for the page data importer
30 * implements Special:Import
31 * @ingroup SpecialPage
34 private $reader = null;
35 private $foreignNamespaces = null;
36 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
37 private $mSiteInfoCallback, $mTargetNamespace, $mPageOutCallback;
38 private $mNoticeCallback, $mDebug;
39 private $mImportUploads, $mImageBasePath;
40 private $mNoUpdates = false;
43 /** @var ImportTitleFactory */
44 private $importTitleFactory;
46 private $countableCache = array();
49 * Creates an ImportXMLReader drawing from the source provided
50 * @param ImportSource $source
51 * @param Config $config
54 function __construct( ImportSource
$source, Config
$config = null ) {
55 if ( !class_exists( 'XMLReader' ) ) {
56 throw new Exception( 'Import requires PHP to have been compiled with libxml support' );
59 $this->reader
= new XMLReader();
61 wfDeprecated( __METHOD__
. ' without a Config instance', '1.25' );
62 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
64 $this->config
= $config;
66 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
67 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
69 $id = UploadSourceAdapter
::registerSource( $source );
71 // Enable the entity loader, as it is needed for loading external URLs via
72 // XMLReader::open (T86036)
73 $oldDisable = libxml_disable_entity_loader( false );
74 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
75 $status = $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
77 $status = $this->reader
->open( "uploadsource://$id" );
80 $error = libxml_get_last_error();
81 libxml_disable_entity_loader( $oldDisable );
82 throw new MWException( 'Encountered an internal error while initializing WikiImporter object: ' .
85 libxml_disable_entity_loader( $oldDisable );
88 $this->setPageCallback( array( $this, 'beforeImportPage' ) );
89 $this->setRevisionCallback( array( $this, "importRevision" ) );
90 $this->setUploadCallback( array( $this, 'importUpload' ) );
91 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
92 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
94 $this->importTitleFactory
= new NaiveImportTitleFactory();
98 * @return null|XMLReader
100 public function getReader() {
101 return $this->reader
;
104 public function throwXmlError( $err ) {
105 $this->debug( "FAILURE: $err" );
106 wfDebug( "WikiImporter XML error: $err\n" );
109 public function debug( $data ) {
110 if ( $this->mDebug
) {
111 wfDebug( "IMPORT: $data\n" );
115 public function warn( $data ) {
116 wfDebug( "IMPORT: $data\n" );
119 public function notice( $msg /*, $param, ...*/ ) {
120 $params = func_get_args();
121 array_shift( $params );
123 if ( is_callable( $this->mNoticeCallback
) ) {
124 call_user_func( $this->mNoticeCallback
, $msg, $params );
125 } else { # No ImportReporter -> CLI
126 echo wfMessage( $msg, $params )->text() . "\n";
134 function setDebug( $debug ) {
135 $this->mDebug
= $debug;
139 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
140 * @param bool $noupdates
142 function setNoUpdates( $noupdates ) {
143 $this->mNoUpdates
= $noupdates;
147 * Set a callback that displays notice messages
149 * @param callable $callback
152 public function setNoticeCallback( $callback ) {
153 return wfSetVar( $this->mNoticeCallback
, $callback );
157 * Sets the action to perform as each new page in the stream is reached.
158 * @param callable $callback
161 public function setPageCallback( $callback ) {
162 $previous = $this->mPageCallback
;
163 $this->mPageCallback
= $callback;
168 * Sets the action to perform as each page in the stream is completed.
169 * Callback accepts the page title (as a Title object), a second object
170 * with the original title form (in case it's been overridden into a
171 * local namespace), and a count of revisions.
173 * @param callable $callback
176 public function setPageOutCallback( $callback ) {
177 $previous = $this->mPageOutCallback
;
178 $this->mPageOutCallback
= $callback;
183 * Sets the action to perform as each page revision is reached.
184 * @param callable $callback
187 public function setRevisionCallback( $callback ) {
188 $previous = $this->mRevisionCallback
;
189 $this->mRevisionCallback
= $callback;
194 * Sets the action to perform as each file upload version is reached.
195 * @param callable $callback
198 public function setUploadCallback( $callback ) {
199 $previous = $this->mUploadCallback
;
200 $this->mUploadCallback
= $callback;
205 * Sets the action to perform as each log item reached.
206 * @param callable $callback
209 public function setLogItemCallback( $callback ) {
210 $previous = $this->mLogItemCallback
;
211 $this->mLogItemCallback
= $callback;
216 * Sets the action to perform when site info is encountered
217 * @param callable $callback
220 public function setSiteInfoCallback( $callback ) {
221 $previous = $this->mSiteInfoCallback
;
222 $this->mSiteInfoCallback
= $callback;
227 * Sets the factory object to use to convert ForeignTitle objects into local
229 * @param ImportTitleFactory $factory
231 public function setImportTitleFactory( $factory ) {
232 $this->importTitleFactory
= $factory;
236 * Set a target namespace to override the defaults
237 * @param null|int $namespace
240 public function setTargetNamespace( $namespace ) {
241 if ( is_null( $namespace ) ) {
242 // Don't override namespaces
243 $this->mTargetNamespace
= null;
244 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
248 MWNamespace
::exists( intval( $namespace ) )
250 $namespace = intval( $namespace );
251 $this->mTargetNamespace
= $namespace;
252 $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
260 * Set a target root page under which all pages are imported
261 * @param null|string $rootpage
264 public function setTargetRootPage( $rootpage ) {
265 $status = Status
::newGood();
266 if ( is_null( $rootpage ) ) {
268 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
269 } elseif ( $rootpage !== '' ) {
270 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
271 $title = Title
::newFromText( $rootpage, !is_null( $this->mTargetNamespace
)
272 ?
$this->mTargetNamespace
276 if ( !$title ||
$title->isExternal() ) {
277 $status->fatal( 'import-rootpage-invalid' );
279 if ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
282 $displayNSText = $title->getNamespace() == NS_MAIN
283 ?
wfMessage( 'blanknamespace' )->text()
284 : $wgContLang->getNsText( $title->getNamespace() );
285 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
287 // set namespace to 'all', so the namespace check in processTitle() can pass
288 $this->setTargetNamespace( null );
289 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
299 public function setImageBasePath( $dir ) {
300 $this->mImageBasePath
= $dir;
304 * @param bool $import
306 public function setImportUploads( $import ) {
307 $this->mImportUploads
= $import;
311 * Default per-page callback. Sets up some things related to site statistics
312 * @param array $titleAndForeignTitle Two-element array, with Title object at
313 * index 0 and ForeignTitle object at index 1
316 public function beforeImportPage( $titleAndForeignTitle ) {
317 $title = $titleAndForeignTitle[0];
318 $page = WikiPage
::factory( $title );
319 $this->countableCache
['title_' . $title->getPrefixedText()] = $page->isCountable();
324 * Default per-revision callback, performs the import.
325 * @param WikiRevision $revision
328 public function importRevision( $revision ) {
329 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
330 $this->notice( 'import-error-bad-location',
331 $revision->getTitle()->getPrefixedText(),
333 $revision->getModel(),
334 $revision->getFormat() );
340 $dbw = wfGetDB( DB_MASTER
);
341 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
342 } catch ( MWContentSerializationException
$ex ) {
343 $this->notice( 'import-error-unserialize',
344 $revision->getTitle()->getPrefixedText(),
346 $revision->getModel(),
347 $revision->getFormat() );
354 * Default per-revision callback, performs the import.
355 * @param WikiRevision $revision
358 public function importLogItem( $revision ) {
359 $dbw = wfGetDB( DB_MASTER
);
360 return $dbw->deadlockLoop( array( $revision, 'importLogItem' ) );
365 * @param WikiRevision $revision
368 public function importUpload( $revision ) {
369 $dbw = wfGetDB( DB_MASTER
);
370 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
374 * Mostly for hook use
375 * @param Title $title
376 * @param ForeignTitle $foreignTitle
377 * @param int $revCount
378 * @param int $sRevCount
379 * @param array $pageInfo
382 public function finishImportPage( $title, $foreignTitle, $revCount,
383 $sRevCount, $pageInfo ) {
385 // Update article count statistics (T42009)
386 // The normal counting logic in WikiPage->doEditUpdates() is designed for
387 // one-revision-at-a-time editing, not bulk imports. In this situation it
388 // suffers from issues of slave lag. We let WikiPage handle the total page
389 // and revision count, and we implement our own custom logic for the
390 // article (content page) count.
391 $page = WikiPage
::factory( $title );
392 $page->loadPageData( 'fromdbmaster' );
393 $content = $page->getContent();
394 if ( $content === null ) {
395 wfDebug( __METHOD__
. ': Skipping article count adjustment for ' . $title .
396 ' because WikiPage::getContent() returned null' );
398 $editInfo = $page->prepareContentForEdit( $content );
399 $countKey = 'title_' . $title->getPrefixedText();
400 $countable = $page->isCountable( $editInfo );
401 if ( array_key_exists( $countKey, $this->countableCache
) &&
402 $countable != $this->countableCache
[ $countKey ] ) {
403 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array(
404 'articles' => ( (int)$countable - (int)$this->countableCache
[ $countKey ] )
409 $args = func_get_args();
410 return Hooks
::run( 'AfterImportPage', $args );
414 * Alternate per-revision callback, for debugging.
415 * @param WikiRevision $revision
417 public function debugRevisionHandler( &$revision ) {
418 $this->debug( "Got revision:" );
419 if ( is_object( $revision->title
) ) {
420 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
422 $this->debug( "-- Title: <invalid>" );
424 $this->debug( "-- User: " . $revision->user_text
);
425 $this->debug( "-- Timestamp: " . $revision->timestamp
);
426 $this->debug( "-- Comment: " . $revision->comment
);
427 $this->debug( "-- Text: " . $revision->text
);
431 * Notify the callback function of site info
432 * @param array $siteInfo
435 private function siteInfoCallback( $siteInfo ) {
436 if ( isset( $this->mSiteInfoCallback
) ) {
437 return call_user_func_array( $this->mSiteInfoCallback
,
438 array( $siteInfo, $this ) );
445 * Notify the callback function when a new "<page>" is reached.
446 * @param Title $title
448 function pageCallback( $title ) {
449 if ( isset( $this->mPageCallback
) ) {
450 call_user_func( $this->mPageCallback
, $title );
455 * Notify the callback function when a "</page>" is closed.
456 * @param Title $title
457 * @param ForeignTitle $foreignTitle
458 * @param int $revCount
459 * @param int $sucCount Number of revisions for which callback returned true
460 * @param array $pageInfo Associative array of page information
462 private function pageOutCallback( $title, $foreignTitle, $revCount,
463 $sucCount, $pageInfo ) {
464 if ( isset( $this->mPageOutCallback
) ) {
465 $args = func_get_args();
466 call_user_func_array( $this->mPageOutCallback
, $args );
471 * Notify the callback function of a revision
472 * @param WikiRevision $revision
475 private function revisionCallback( $revision ) {
476 if ( isset( $this->mRevisionCallback
) ) {
477 return call_user_func_array( $this->mRevisionCallback
,
478 array( $revision, $this ) );
485 * Notify the callback function of a new log item
486 * @param WikiRevision $revision
489 private function logItemCallback( $revision ) {
490 if ( isset( $this->mLogItemCallback
) ) {
491 return call_user_func_array( $this->mLogItemCallback
,
492 array( $revision, $this ) );
499 * Retrieves the contents of the named attribute of the current element.
500 * @param string $attr The name of the attribute
501 * @return string The value of the attribute or an empty string if it is not set in the current
504 public function nodeAttribute( $attr ) {
505 return $this->reader
->getAttribute( $attr );
509 * Shouldn't something like this be built-in to XMLReader?
510 * Fetches text contents of the current element, assuming
511 * no sub-elements or such scary things.
515 public function nodeContents() {
516 if ( $this->reader
->isEmptyElement
) {
520 while ( $this->reader
->read() ) {
521 switch ( $this->reader
->nodeType
) {
522 case XMLReader
::TEXT
:
523 case XMLReader
::SIGNIFICANT_WHITESPACE
:
524 $buffer .= $this->reader
->value
;
526 case XMLReader
::END_ELEMENT
:
531 $this->reader
->close();
536 * Primary entry point
537 * @throws MWException
540 public function doImport() {
541 // Calls to reader->read need to be wrapped in calls to
542 // libxml_disable_entity_loader() to avoid local file
543 // inclusion attacks (bug 46932).
544 $oldDisable = libxml_disable_entity_loader( true );
545 $this->reader
->read();
547 if ( $this->reader
->localName
!= 'mediawiki' ) {
548 libxml_disable_entity_loader( $oldDisable );
549 throw new MWException( "Expected <mediawiki> tag, got " .
550 $this->reader
->localName
);
552 $this->debug( "<mediawiki> tag is correct." );
554 $this->debug( "Starting primary dump processing loop." );
556 $keepReading = $this->reader
->read();
560 while ( $keepReading ) {
561 $tag = $this->reader
->localName
;
562 $type = $this->reader
->nodeType
;
564 if ( !Hooks
::run( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
566 } elseif ( $tag == 'mediawiki' && $type == XMLReader
::END_ELEMENT
) {
568 } elseif ( $tag == 'siteinfo' ) {
569 $this->handleSiteInfo();
570 } elseif ( $tag == 'page' ) {
572 } elseif ( $tag == 'logitem' ) {
573 $this->handleLogItem();
574 } elseif ( $tag != '#text' ) {
575 $this->warn( "Unhandled top-level XML tag $tag" );
581 $keepReading = $this->reader
->next();
583 $this->debug( "Skip" );
585 $keepReading = $this->reader
->read();
588 } catch ( Exception
$ex ) {
593 libxml_disable_entity_loader( $oldDisable );
594 $this->reader
->close();
603 private function handleSiteInfo() {
604 $this->debug( "Enter site info handler." );
607 // Fields that can just be stuffed in the siteInfo object
608 $normalFields = array( 'sitename', 'base', 'generator', 'case' );
610 while ( $this->reader
->read() ) {
611 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
612 $this->reader
->localName
== 'siteinfo' ) {
616 $tag = $this->reader
->localName
;
618 if ( $tag == 'namespace' ) {
619 $this->foreignNamespaces
[ $this->nodeAttribute( 'key' ) ] =
620 $this->nodeContents();
621 } elseif ( in_array( $tag, $normalFields ) ) {
622 $siteInfo[$tag] = $this->nodeContents();
626 $siteInfo['_namespaces'] = $this->foreignNamespaces
;
627 $this->siteInfoCallback( $siteInfo );
630 private function handleLogItem() {
631 $this->debug( "Enter log item handler." );
634 // Fields that can just be stuffed in the pageInfo object
635 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
636 'logtitle', 'params' );
638 while ( $this->reader
->read() ) {
639 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
640 $this->reader
->localName
== 'logitem' ) {
644 $tag = $this->reader
->localName
;
646 if ( !Hooks
::run( 'ImportHandleLogItemXMLTag', array(
650 } elseif ( in_array( $tag, $normalFields ) ) {
651 $logInfo[$tag] = $this->nodeContents();
652 } elseif ( $tag == 'contributor' ) {
653 $logInfo['contributor'] = $this->handleContributor();
654 } elseif ( $tag != '#text' ) {
655 $this->warn( "Unhandled log-item XML tag $tag" );
659 $this->processLogItem( $logInfo );
663 * @param array $logInfo
666 private function processLogItem( $logInfo ) {
667 $revision = new WikiRevision( $this->config
);
669 $revision->setID( $logInfo['id'] );
670 $revision->setType( $logInfo['type'] );
671 $revision->setAction( $logInfo['action'] );
672 $revision->setTimestamp( $logInfo['timestamp'] );
673 $revision->setParams( $logInfo['params'] );
674 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
675 $revision->setNoUpdates( $this->mNoUpdates
);
677 if ( isset( $logInfo['comment'] ) ) {
678 $revision->setComment( $logInfo['comment'] );
681 if ( isset( $logInfo['contributor']['ip'] ) ) {
682 $revision->setUserIP( $logInfo['contributor']['ip'] );
684 if ( isset( $logInfo['contributor']['username'] ) ) {
685 $revision->setUserName( $logInfo['contributor']['username'] );
688 return $this->logItemCallback( $revision );
691 private function handlePage() {
693 $this->debug( "Enter page handler." );
694 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
696 // Fields that can just be stuffed in the pageInfo object
697 $normalFields = array( 'title', 'ns', 'id', 'redirect', 'restrictions' );
702 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
703 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
704 $this->reader
->localName
== 'page' ) {
710 $tag = $this->reader
->localName
;
713 // The title is invalid, bail out of this page
715 } elseif ( !Hooks
::run( 'ImportHandlePageXMLTag', array( $this,
718 } elseif ( in_array( $tag, $normalFields ) ) {
722 // <title>Page</title>
723 // <redirect title="NewTitle"/>
725 // Because the redirect tag is built differently, we need special handling for that case.
726 if ( $tag == 'redirect' ) {
727 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
729 $pageInfo[$tag] = $this->nodeContents();
731 } elseif ( $tag == 'revision' ||
$tag == 'upload' ) {
732 if ( !isset( $title ) ) {
733 $title = $this->processTitle( $pageInfo['title'],
734 isset( $pageInfo['ns'] ) ?
$pageInfo['ns'] : null );
741 $this->pageCallback( $title );
742 list( $pageInfo['_title'], $foreignTitle ) = $title;
746 if ( $tag == 'revision' ) {
747 $this->handleRevision( $pageInfo );
749 $this->handleUpload( $pageInfo );
752 } elseif ( $tag != '#text' ) {
753 $this->warn( "Unhandled page XML tag $tag" );
758 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
759 $pageInfo['revisionCount'],
760 $pageInfo['successfulRevisionCount'],
765 * @param array $pageInfo
767 private function handleRevision( &$pageInfo ) {
768 $this->debug( "Enter revision handler" );
769 $revisionInfo = array();
771 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
775 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
776 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
777 $this->reader
->localName
== 'revision' ) {
781 $tag = $this->reader
->localName
;
783 if ( !Hooks
::run( 'ImportHandleRevisionXMLTag', array(
784 $this, $pageInfo, $revisionInfo
787 } elseif ( in_array( $tag, $normalFields ) ) {
788 $revisionInfo[$tag] = $this->nodeContents();
789 } elseif ( $tag == 'contributor' ) {
790 $revisionInfo['contributor'] = $this->handleContributor();
791 } elseif ( $tag != '#text' ) {
792 $this->warn( "Unhandled revision XML tag $tag" );
797 $pageInfo['revisionCount']++
;
798 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
799 $pageInfo['successfulRevisionCount']++
;
804 * @param array $pageInfo
805 * @param array $revisionInfo
808 private function processRevision( $pageInfo, $revisionInfo ) {
809 $revision = new WikiRevision( $this->config
);
811 if ( isset( $revisionInfo['id'] ) ) {
812 $revision->setID( $revisionInfo['id'] );
814 if ( isset( $revisionInfo['model'] ) ) {
815 $revision->setModel( $revisionInfo['model'] );
817 if ( isset( $revisionInfo['format'] ) ) {
818 $revision->setFormat( $revisionInfo['format'] );
820 $revision->setTitle( $pageInfo['_title'] );
822 if ( isset( $revisionInfo['text'] ) ) {
823 $handler = $revision->getContentHandler();
824 $text = $handler->importTransform(
825 $revisionInfo['text'],
826 $revision->getFormat() );
828 $revision->setText( $text );
830 if ( isset( $revisionInfo['timestamp'] ) ) {
831 $revision->setTimestamp( $revisionInfo['timestamp'] );
833 $revision->setTimestamp( wfTimestampNow() );
836 if ( isset( $revisionInfo['comment'] ) ) {
837 $revision->setComment( $revisionInfo['comment'] );
840 if ( isset( $revisionInfo['minor'] ) ) {
841 $revision->setMinor( true );
843 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
844 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
846 if ( isset( $revisionInfo['contributor']['username'] ) ) {
847 $revision->setUserName( $revisionInfo['contributor']['username'] );
849 $revision->setNoUpdates( $this->mNoUpdates
);
851 return $this->revisionCallback( $revision );
855 * @param array $pageInfo
858 private function handleUpload( &$pageInfo ) {
859 $this->debug( "Enter upload handler" );
860 $uploadInfo = array();
862 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
863 'src', 'size', 'sha1base36', 'archivename', 'rel' );
867 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
868 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
869 $this->reader
->localName
== 'upload' ) {
873 $tag = $this->reader
->localName
;
875 if ( !Hooks
::run( 'ImportHandleUploadXMLTag', array(
879 } elseif ( in_array( $tag, $normalFields ) ) {
880 $uploadInfo[$tag] = $this->nodeContents();
881 } elseif ( $tag == 'contributor' ) {
882 $uploadInfo['contributor'] = $this->handleContributor();
883 } elseif ( $tag == 'contents' ) {
884 $contents = $this->nodeContents();
885 $encoding = $this->reader
->getAttribute( 'encoding' );
886 if ( $encoding === 'base64' ) {
887 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
888 $uploadInfo['isTempSrc'] = true;
890 } elseif ( $tag != '#text' ) {
891 $this->warn( "Unhandled upload XML tag $tag" );
896 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
897 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
898 if ( file_exists( $path ) ) {
899 $uploadInfo['fileSrc'] = $path;
900 $uploadInfo['isTempSrc'] = false;
904 if ( $this->mImportUploads
) {
905 return $this->processUpload( $pageInfo, $uploadInfo );
910 * @param string $contents
913 private function dumpTemp( $contents ) {
914 $filename = tempnam( wfTempDir(), 'importupload' );
915 file_put_contents( $filename, $contents );
920 * @param array $pageInfo
921 * @param array $uploadInfo
924 private function processUpload( $pageInfo, $uploadInfo ) {
925 $revision = new WikiRevision( $this->config
);
926 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
928 $revision->setTitle( $pageInfo['_title'] );
929 $revision->setID( $pageInfo['id'] );
930 $revision->setTimestamp( $uploadInfo['timestamp'] );
931 $revision->setText( $text );
932 $revision->setFilename( $uploadInfo['filename'] );
933 if ( isset( $uploadInfo['archivename'] ) ) {
934 $revision->setArchiveName( $uploadInfo['archivename'] );
936 $revision->setSrc( $uploadInfo['src'] );
937 if ( isset( $uploadInfo['fileSrc'] ) ) {
938 $revision->setFileSrc( $uploadInfo['fileSrc'],
939 !empty( $uploadInfo['isTempSrc'] ) );
941 if ( isset( $uploadInfo['sha1base36'] ) ) {
942 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
944 $revision->setSize( intval( $uploadInfo['size'] ) );
945 $revision->setComment( $uploadInfo['comment'] );
947 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
948 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
950 if ( isset( $uploadInfo['contributor']['username'] ) ) {
951 $revision->setUserName( $uploadInfo['contributor']['username'] );
953 $revision->setNoUpdates( $this->mNoUpdates
);
955 return call_user_func( $this->mUploadCallback
, $revision );
961 private function handleContributor() {
962 $fields = array( 'id', 'ip', 'username' );
965 while ( $this->reader
->read() ) {
966 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
967 $this->reader
->localName
== 'contributor' ) {
971 $tag = $this->reader
->localName
;
973 if ( in_array( $tag, $fields ) ) {
974 $info[$tag] = $this->nodeContents();
982 * @param string $text
983 * @param string|null $ns
986 private function processTitle( $text, $ns = null ) {
987 if ( is_null( $this->foreignNamespaces
) ) {
988 $foreignTitleFactory = new NaiveForeignTitleFactory();
990 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
991 $this->foreignNamespaces
);
994 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
997 $title = $this->importTitleFactory
->createTitleFromForeignTitle(
1000 $commandLineMode = $this->config
->get( 'CommandLineMode' );
1001 if ( is_null( $title ) ) {
1002 # Invalid page title? Ignore the page
1003 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
1005 } elseif ( $title->isExternal() ) {
1006 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1008 } elseif ( !$title->canExist() ) {
1009 $this->notice( 'import-error-special', $title->getPrefixedText() );
1011 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
1012 # Do not import if the importing wiki user cannot edit this page
1013 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1015 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
1016 # Do not import if the importing wiki user cannot create this page
1017 $this->notice( 'import-error-create', $title->getPrefixedText() );
1021 return array( $title, $foreignTitle );
1025 /** This is a horrible hack used to keep source compatibility */
1026 class UploadSourceAdapter
{
1028 public static $sourceRegistrations = array();
1040 * @param ImportSource $source
1043 static function registerSource( ImportSource
$source ) {
1044 $id = wfRandomString();
1046 self
::$sourceRegistrations[$id] = $source;
1052 * @param string $path
1053 * @param string $mode
1054 * @param array $options
1055 * @param string $opened_path
1058 function stream_open( $path, $mode, $options, &$opened_path ) {
1059 $url = parse_url( $path );
1062 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
1066 $this->mSource
= self
::$sourceRegistrations[$id];
1075 function stream_read( $count ) {
1079 while ( !$leave && !$this->mSource
->atEnd() &&
1080 strlen( $this->mBuffer
) < $count ) {
1081 $read = $this->mSource
->readChunk();
1083 if ( !strlen( $read ) ) {
1087 $this->mBuffer
.= $read;
1090 if ( strlen( $this->mBuffer
) ) {
1091 $return = substr( $this->mBuffer
, 0, $count );
1092 $this->mBuffer
= substr( $this->mBuffer
, $count );
1095 $this->mPosition +
= strlen( $return );
1101 * @param string $data
1104 function stream_write( $data ) {
1111 function stream_tell() {
1112 return $this->mPosition
;
1118 function stream_eof() {
1119 return $this->mSource
->atEnd();
1125 function url_stat() {
1128 $result['dev'] = $result[0] = 0;
1129 $result['ino'] = $result[1] = 0;
1130 $result['mode'] = $result[2] = 0;
1131 $result['nlink'] = $result[3] = 0;
1132 $result['uid'] = $result[4] = 0;
1133 $result['gid'] = $result[5] = 0;
1134 $result['rdev'] = $result[6] = 0;
1135 $result['size'] = $result[7] = 0;
1136 $result['atime'] = $result[8] = 0;
1137 $result['mtime'] = $result[9] = 0;
1138 $result['ctime'] = $result[10] = 0;
1139 $result['blksize'] = $result[11] = 0;
1140 $result['blocks'] = $result[12] = 0;
1147 * @todo document (e.g. one-sentence class description).
1148 * @ingroup SpecialPage
1150 class WikiRevision
{
1151 /** @todo Unused? */
1152 public $importer = null;
1155 public $title = null;
1161 public $timestamp = "20010115000000";
1165 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1169 public $user_text = "";
1172 public $model = null;
1175 public $format = null;
1184 public $content = null;
1186 /** @var ContentHandler */
1187 protected $contentHandler = null;
1190 public $comment = "";
1193 public $minor = false;
1199 public $action = "";
1202 public $params = "";
1205 public $fileSrc = '';
1207 /** @var bool|string */
1208 public $sha1base36 = false;
1214 public $isTemp = false;
1217 public $archiveName = '';
1219 protected $filename;
1224 /** @todo Unused? */
1228 private $mNoUpdates = false;
1230 /** @var Config $config */
1233 public function __construct( Config
$config ) {
1234 $this->config
= $config;
1238 * @param Title $title
1239 * @throws MWException
1241 function setTitle( $title ) {
1242 if ( is_object( $title ) ) {
1243 $this->title
= $title;
1244 } elseif ( is_null( $title ) ) {
1245 throw new MWException( "WikiRevision given a null title in import. "
1246 . "You may need to adjust \$wgLegalTitleChars." );
1248 throw new MWException( "WikiRevision given non-object title in import." );
1255 function setID( $id ) {
1262 function setTimestamp( $ts ) {
1263 # 2003-08-05T18:30:02Z
1264 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1268 * @param string $user
1270 function setUsername( $user ) {
1271 $this->user_text
= $user;
1277 function setUserIP( $ip ) {
1278 $this->user_text
= $ip;
1282 * @param string $model
1284 function setModel( $model ) {
1285 $this->model
= $model;
1289 * @param string $format
1291 function setFormat( $format ) {
1292 $this->format
= $format;
1296 * @param string $text
1298 function setText( $text ) {
1299 $this->text
= $text;
1303 * @param string $text
1305 function setComment( $text ) {
1306 $this->comment
= $text;
1310 * @param bool $minor
1312 function setMinor( $minor ) {
1313 $this->minor
= (bool)$minor;
1319 function setSrc( $src ) {
1324 * @param string $src
1325 * @param bool $isTemp
1327 function setFileSrc( $src, $isTemp ) {
1328 $this->fileSrc
= $src;
1329 $this->fileIsTemp
= $isTemp;
1333 * @param string $sha1base36
1335 function setSha1Base36( $sha1base36 ) {
1336 $this->sha1base36
= $sha1base36;
1340 * @param string $filename
1342 function setFilename( $filename ) {
1343 $this->filename
= $filename;
1347 * @param string $archiveName
1349 function setArchiveName( $archiveName ) {
1350 $this->archiveName
= $archiveName;
1356 function setSize( $size ) {
1357 $this->size
= intval( $size );
1361 * @param string $type
1363 function setType( $type ) {
1364 $this->type
= $type;
1368 * @param string $action
1370 function setAction( $action ) {
1371 $this->action
= $action;
1375 * @param array $params
1377 function setParams( $params ) {
1378 $this->params
= $params;
1382 * @param bool $noupdates
1384 public function setNoUpdates( $noupdates ) {
1385 $this->mNoUpdates
= $noupdates;
1391 function getTitle() {
1392 return $this->title
;
1405 function getTimestamp() {
1406 return $this->timestamp
;
1412 function getUser() {
1413 return $this->user_text
;
1419 * @deprecated Since 1.21, use getContent() instead.
1421 function getText() {
1422 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1428 * @return ContentHandler
1430 function getContentHandler() {
1431 if ( is_null( $this->contentHandler
) ) {
1432 $this->contentHandler
= ContentHandler
::getForModelID( $this->getModel() );
1435 return $this->contentHandler
;
1441 function getContent() {
1442 if ( is_null( $this->content
) ) {
1443 $handler = $this->getContentHandler();
1444 $this->content
= $handler->unserializeContent( $this->text
, $this->getFormat() );
1447 return $this->content
;
1453 function getModel() {
1454 if ( is_null( $this->model
) ) {
1455 $this->model
= $this->getTitle()->getContentModel();
1458 return $this->model
;
1464 function getFormat() {
1465 if ( is_null( $this->format
) ) {
1466 $this->format
= $this->getContentHandler()->getDefaultFormat();
1469 return $this->format
;
1475 function getComment() {
1476 return $this->comment
;
1482 function getMinor() {
1483 return $this->minor
;
1494 * @return bool|string
1496 function getSha1() {
1497 if ( $this->sha1base36
) {
1498 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1506 function getFileSrc() {
1507 return $this->fileSrc
;
1513 function isTempSrc() {
1514 return $this->isTemp
;
1520 function getFilename() {
1521 return $this->filename
;
1527 function getArchiveName() {
1528 return $this->archiveName
;
1534 function getSize() {
1541 function getType() {
1548 function getAction() {
1549 return $this->action
;
1555 function getParams() {
1556 return $this->params
;
1562 function importOldRevision() {
1563 $dbw = wfGetDB( DB_MASTER
);
1565 # Sneak a single revision into place
1566 $user = User
::newFromName( $this->getUser() );
1568 $userId = intval( $user->getId() );
1569 $userText = $user->getName();
1573 $userText = $this->getUser();
1574 $userObj = new User
;
1577 // avoid memory leak...?
1578 $linkCache = LinkCache
::singleton();
1579 $linkCache->clear();
1581 $page = WikiPage
::factory( $this->title
);
1582 $page->loadPageData( 'fromdbmaster' );
1583 if ( !$page->exists() ) {
1584 # must create the page...
1585 $pageId = $page->insertOn( $dbw );
1587 $oldcountable = null;
1589 $pageId = $page->getId();
1592 $prior = $dbw->selectField( 'revision', '1',
1593 array( 'rev_page' => $pageId,
1594 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1595 'rev_user_text' => $userText,
1596 'rev_comment' => $this->getComment() ),
1600 // @todo FIXME: This could fail slightly for multiple matches :P
1601 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1602 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1607 # @todo FIXME: Use original rev_id optionally (better for backups)
1609 $revision = new Revision( array(
1610 'title' => $this->title
,
1612 'content_model' => $this->getModel(),
1613 'content_format' => $this->getFormat(),
1614 //XXX: just set 'content' => $this->getContent()?
1615 'text' => $this->getContent()->serialize( $this->getFormat() ),
1616 'comment' => $this->getComment(),
1618 'user_text' => $userText,
1619 'timestamp' => $this->timestamp
,
1620 'minor_edit' => $this->minor
,
1622 $revision->insertOn( $dbw );
1623 $changed = $page->updateIfNewerOn( $dbw, $revision );
1625 if ( $changed !== false && !$this->mNoUpdates
) {
1626 wfDebug( __METHOD__
. ": running updates\n" );
1627 // countable/oldcountable stuff is handled in WikiImporter::finishImportPage
1628 $page->doEditUpdates(
1631 array( 'created' => $created, 'oldcountable' => 'no-change' )
1638 function importLogItem() {
1639 $dbw = wfGetDB( DB_MASTER
);
1640 # @todo FIXME: This will not record autoblocks
1641 if ( !$this->getTitle() ) {
1642 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1643 $this->timestamp
. "\n" );
1646 # Check if it exists already
1647 // @todo FIXME: Use original log ID (better for backups)
1648 $prior = $dbw->selectField( 'logging', '1',
1649 array( 'log_type' => $this->getType(),
1650 'log_action' => $this->getAction(),
1651 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1652 'log_namespace' => $this->getTitle()->getNamespace(),
1653 'log_title' => $this->getTitle()->getDBkey(),
1654 'log_comment' => $this->getComment(),
1655 #'log_user_text' => $this->user_text,
1656 'log_params' => $this->params
),
1659 // @todo FIXME: This could fail slightly for multiple matches :P
1662 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1663 . $this->timestamp
. "\n" );
1666 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1668 'log_id' => $log_id,
1669 'log_type' => $this->type
,
1670 'log_action' => $this->action
,
1671 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1672 'log_user' => User
::idFromName( $this->user_text
),
1673 #'log_user_text' => $this->user_text,
1674 'log_namespace' => $this->getTitle()->getNamespace(),
1675 'log_title' => $this->getTitle()->getDBkey(),
1676 'log_comment' => $this->getComment(),
1677 'log_params' => $this->params
1679 $dbw->insert( 'logging', $data, __METHOD__
);
1685 function importUpload() {
1687 $archiveName = $this->getArchiveName();
1688 if ( $archiveName ) {
1689 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1690 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1691 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1693 $file = wfLocalFile( $this->getTitle() );
1694 $file->load( File
::READ_LATEST
);
1695 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1696 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1697 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1698 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1699 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1700 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1704 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1708 # Get the file source or download if necessary
1709 $source = $this->getFileSrc();
1710 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1712 $source = $this->downloadSource();
1713 $flags |
= File
::DELETE_SOURCE
;
1716 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1719 $sha1 = $this->getSha1();
1720 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1721 if ( $flags & File
::DELETE_SOURCE
) {
1722 # Broken file; delete it if it is a temporary file
1725 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1729 $user = User
::newFromName( $this->user_text
);
1731 # Do the actual upload
1732 if ( $archiveName ) {
1733 $status = $file->uploadOld( $source, $archiveName,
1734 $this->getTimestamp(), $this->getComment(), $user, $flags );
1736 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1737 $flags, false, $this->getTimestamp(), $user );
1740 if ( $status->isGood() ) {
1741 wfDebug( __METHOD__
. ": Successful\n" );
1744 wfDebug( __METHOD__
. ': failed: ' . $status->getHTML() . "\n" );
1750 * @return bool|string
1752 function downloadSource() {
1753 if ( !$this->config
->get( 'EnableUploads' ) ) {
1757 $tempo = tempnam( wfTempDir(), 'download' );
1758 $f = fopen( $tempo, 'wb' );
1760 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1765 $src = $this->getSrc();
1766 $data = Http
::get( $src, array(), __METHOD__
);
1768 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1774 fwrite( $f, $data );
1783 * Source interface for XML import.
1785 interface ImportSource
{
1788 * Indicates whether the end of the input has been reached.
1789 * Will return true after a finite number of calls to readChunk.
1791 * @return bool true if there is no more input, false otherwise.
1796 * Return a chunk of the input, as a (possibly empty) string.
1797 * When the end of input is reached, readChunk() returns false.
1798 * If atEnd() returns false, readChunk() will return a string.
1799 * If atEnd() returns true, readChunk() will return false.
1801 * @return bool|string
1803 function readChunk();
1807 * Used for importing XML dumps where the content of the dump is in a string.
1808 * This class is ineffecient, and should only be used for small dumps.
1809 * For larger dumps, ImportStreamSource should be used instead.
1811 * @ingroup SpecialPage
1813 class ImportStringSource
implements ImportSource
{
1814 function __construct( $string ) {
1815 $this->mString
= $string;
1816 $this->mRead
= false;
1823 return $this->mRead
;
1827 * @return bool|string
1829 function readChunk() {
1830 if ( $this->atEnd() ) {
1833 $this->mRead
= true;
1834 return $this->mString
;
1839 * Imports a XML dump from a file (either from file upload, files on disk, or HTTP)
1840 * @ingroup SpecialPage
1842 class ImportStreamSource
implements ImportSource
{
1843 function __construct( $handle ) {
1844 $this->mHandle
= $handle;
1851 return feof( $this->mHandle
);
1857 function readChunk() {
1858 return fread( $this->mHandle
, 32768 );
1862 * @param string $filename
1865 static function newFromFile( $filename ) {
1866 wfSuppressWarnings();
1867 $file = fopen( $filename, 'rt' );
1868 wfRestoreWarnings();
1870 return Status
::newFatal( "importcantopen" );
1872 return Status
::newGood( new ImportStreamSource( $file ) );
1876 * @param string $fieldname
1879 static function newFromUpload( $fieldname = "xmlimport" ) {
1880 $upload =& $_FILES[$fieldname];
1882 if ( $upload === null ||
!$upload['name'] ) {
1883 return Status
::newFatal( 'importnofile' );
1885 if ( !empty( $upload['error'] ) ) {
1886 switch ( $upload['error'] ) {
1888 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1889 return Status
::newFatal( 'importuploaderrorsize' );
1891 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1892 # was specified in the HTML form.
1893 return Status
::newFatal( 'importuploaderrorsize' );
1895 # The uploaded file was only partially uploaded
1896 return Status
::newFatal( 'importuploaderrorpartial' );
1898 # Missing a temporary folder.
1899 return Status
::newFatal( 'importuploaderrortemp' );
1900 # case else: # Currently impossible
1904 $fname = $upload['tmp_name'];
1905 if ( is_uploaded_file( $fname ) ) {
1906 return ImportStreamSource
::newFromFile( $fname );
1908 return Status
::newFatal( 'importnofile' );
1913 * @param string $url
1914 * @param string $method
1917 static function newFromURL( $url, $method = 'GET' ) {
1918 wfDebug( __METHOD__
. ": opening $url\n" );
1919 # Use the standard HTTP fetch function; it times out
1920 # quicker and sorts out user-agent problems which might
1921 # otherwise prevent importing from large sites, such
1922 # as the Wikimedia cluster, etc.
1923 $data = Http
::request( $method, $url, array( 'followRedirects' => true ), __METHOD__
);
1924 if ( $data !== false ) {
1926 fwrite( $file, $data );
1929 return Status
::newGood( new ImportStreamSource( $file ) );
1931 return Status
::newFatal( 'importcantopen' );
1936 * @param string $interwiki
1937 * @param string $page
1938 * @param bool $history
1939 * @param bool $templates
1940 * @param int $pageLinkDepth
1943 public static function newFromInterwiki( $interwiki, $page, $history = false,
1944 $templates = false, $pageLinkDepth = 0
1946 if ( $page == '' ) {
1947 return Status
::newFatal( 'import-noarticle' );
1949 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1950 if ( is_null( $link ) ||
!$link->isExternal() ) {
1951 return Status
::newFatal( 'importbadinterwiki' );
1955 $params['history'] = 1;
1958 $params['templates'] = 1;
1960 if ( $pageLinkDepth ) {
1961 $params['pagelink-depth'] = $pageLinkDepth;
1963 $url = $link->getFullURL( $params );
1964 # For interwikis, use POST to avoid redirects.
1965 return ImportStreamSource
::newFromURL( $url, "POST" );